﻿//************************************************************************************************
// Copyright © 2003-2012 Steven M. Cohn. All Rights Reserved.
//
// Facility:	Microsoft Development Environment 2012  Version 11.0.50727.1
// Environment:	Microsoft .NET Framework 4.5            Version v4.0.30319
//
// Description: The CookieChipper main
//
// Revision History:
// -Who--------------- -When---------- -What------------------------------------------------------
// Steven M. Cohn		18-Oct-2003		New
// Steven M. Cohn		12-Oct-2004		VS.NET 2005, .NET 2.0
// Steven M. Cohn		20-Nov-2012		Refresh! VS2010 .NET 4.5 64-bit
//************************************************************************************************

namespace CookieChipper
{
	using System;
	using System.Windows.Forms;


	/// <summary>
	/// 
	/// </summary>

	static class Program
	{
		private static bool doCleaning = false;
		private static bool isQuiet = false;

		private static MainWindow window;
		private static Upgrader upgrader;


		/// <summary>
		/// 
		/// </summary>

		[STAThread]
		static void Main ()
		{
			ParseArguments(Environment.GetCommandLineArgs());

			if (doCleaning)
			{
				CleanupCookies();
				return;
			}

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			window = new MainWindow();

			upgrader = new Upgrader(window);
			upgrader.UpgraderCompleted += UpgraderCompleted;
			upgrader.CheckUpgrades();

			Application.Run(window);
		}


		private static void UpgraderCompleted (UpgradeRelease release)
		{
			// release the upgrader when it's done
			upgrader.Dispose();
			upgrader = null;

			using (var dialog = new UpgradeWindow(release))
			{
				DialogResult result = dialog.ShowDialog(window);

				if (result == DialogResult.OK)
				{
					try
					{
						System.Diagnostics.Process.Start(dialog.ReleaseUrl);
					}
					catch
					{
					}
				}
			}
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="args"></param>

		private static void ParseArguments (string[] args)
		{
			string arg;
			for (int i = 0; i < args.Length; i++)
			{
				arg = args[i].Trim().ToLower();

				if (arg.Equals("/clean"))
				{
					doCleaning = true;
				}
				else if (arg.Equals("/quiet"))
				{
					isQuiet = true;
				}
			}
		}


		/// <summary>
		/// 
		/// </summary>

		private static void CleanupCookies ()
		{
			int count = 0;

			try
			{
				var oven = new Oven();

				using (var provider = new CookieCacheProvider())
				{
					count = provider.Clean(oven.IsLocked);
				}
			}
			catch
			{
			}

			if (!isQuiet)
			{
				MessageBox.Show(
					"Cleaned " + count + " cookies from the MSIE cache",
					"Completed",
					MessageBoxButtons.OK,
					MessageBoxIcon.Information);
			}
		}
	}
}